var arrAuths = $("#arrAuths")
    ,arrBtn = [];
var table = layui.table
    ,notifyPerson = 1;
/*
* @author: wj
* @description: 获取选中活动的数据，并且显示
* @date: 2019/3/14 17:50
* @param
* @return
*/
function showNodeDetail() {
    var node = flowchart.currentNode;
    var activityId = $(node).attr("id");

    if ($(node).attr("activity_type") == 'end' || $(node).attr("code") == 'end') {
        $(".endHide").css("display", "none");
        $(".notifyPerson").css("display", "");
        $(".participatetype").css("display", "none");
    } else {
        $(".endHide").css("display", "")
        $(".notifyPerson").css("display", "none");
    }
    if ($(node).attr("code") == '001') {
        $(".view001").css("display", "none");
        $(".view002").css("display", "");
        $(".notifyPerson").css("display", "none");
        $("div.layui-unselect.layui-form-checkbox").css("display", "none");
        $("div.layui-form-item.participatetype").css("display", "none");
    }else if($(node).attr("code") == 'end'){
        $(".view001").css("display", "none");
        $(".view002").css("display", "none");
        $(".notifyPerson").css("display", "");
    }else {
        $(".view001").css("display", "");
        $(".notifyPerson").css("display", "none");
        $("div.layui-form-item.participatetype").css("display", "");
    }
    //打开活动配置页面
    layer.open({
        type: 1
        , content: $('#nodeDetail')
        , resize: false
        , area: ['730px', '580px']
        , title: '【' + $(node).find('.activity_title > div:first').html() + '】活动配置'
        , success: function (layero, index) {   //弹出后回调
            currentLayerIndex = index;
            ActHttpRequest("/wf/activity/" + activityId,{},function(data) {
                if (data.OK != "OK") {
                    layer.alert(data.message);
                    return;
                }
                var iNode = data.wfActivity,
                    partType1 = iNode.participateType ? iNode.participateType : 2,
                    opType2 = iNode.operationType ? iNode.operationType : 4,
                    notifyPerson = iNode.participateType ? iNode.participateType : 1,
                    initVals = {
                        "node_Name": iNode.activityName
                        ,"participateType": partType1
                        ,"operationType": opType2
                        ,"notifyPerson": notifyPerson
                    }
                var strTemp = iNode.activityButtons || "2",
                strTemp = "[" + strTemp + "]";
                arrBtn = JSON.parse(strTemp);
                var newButton = [];
                for (var i = 0,j = arrBtn.length; i < j; i++){
                    if(("2" === partType1 && "1" === opType2) || ("2" === partType1 && "2" === opType2)){
                        if(30 === arrBtn[i] || 40 === arrBtn[i] || 50 === arrBtn[i]){
                            continue;
                        }
                    }
                    newButton.push(arrBtn[i]);
                }
                arrBtn = newButton;
                $.each(arrBtn, function (i, item) {
                    initVals["btnType" + item] = true;
                });
                partType = partType1;
                opType = opType2;
                layForm.val("nodeForm", initVals);
                if (partType == 1) {    //单人参与
                    $("input[name='operationType']").removeAttr("checked")
                    $("input[name='operationType']").attr("disabled", "true")
                } else {    //多人参与
                    $("input[name='operationType']").removeAttr("disabled")
                }
                layForm.render();

                if(iNode.activityCode == "001"){
                    $("div.layui-form-checkbox").each(function () {
                        var val = $(this).prev().val();
                        if(val != "10" && val != "20" && val != "40" && val != "50"){
                            $(this).css("display", "none")
                        }
                    });
                }
            });

            //加载参与者类型
            ActHttpRequest("/wf/activity/authority/list", {
                "activityId": $(flowchart.currentNode).attr("id")
            }, function (data) {

                if (data.OK != "OK") {
                    layer.alert(data.message);
                    return;
                }
                //向权限树传数据
                var authorityJson = []
                $.each(data.List, function (i, item) {

                    item.authType = item.orgName
                    item.role = item.functionId
                    item.activityType = item.flag
                    item.activityId = $(flowchart.currentNode).attr("id")


                    authorityJson.push(item);
                })

                arrAuths.val(JSON.stringify(authorityJson));
                tableAuthInit();
            }, null, null, null, '保存中。。。', true);

        }
        , end: function () {    //销毁后回调
            $('#nodeDetail').css('display', 'none')
            $('#arrAuths').val('[]')
            $("input[lay-filter='btnType']").removeAttr("checked")
            layForm.render();
        }
    });
}

function getActivityAndShow(id, title) {

    showNodeDetail()
}

/*
* ----------------------------------------------------------------------------------------------
* */

/*
* @author: wj
* @description: 节点按钮修改
* @date: 2019/3/14 17:39
* @param
* @return
*/
var layForm = layui.form
layForm.on('checkbox(btnType)', function(data){
    if (data.elem.checked) {
        var ptValue = $("input[name='participateType']:checked").val(), //参与类型
            otValue = $("input[name='operationType']:checked").val(),//操作类型
            checkValue = data.elem.value;
        if(("2" === ptValue && "1" === otValue) || ("2" === ptValue && "2" === otValue)){
            if("30" === checkValue || "40" === checkValue || "50" === checkValue){
                data.elem.checked = false;
                layForm.render("checkbox");
                return;
            }
        }
        var isExist = false;
        $.each(arrBtn, function (i, item) {
            if (data.elem.value == item) {
                isExist = true;
                return false;
            }
        })

        if (isExist == false) arrBtn.push(parseInt(checkValue));

    } else {
        var j = -1;
        $.each(arrBtn, function (i, item) {
            if (data.elem.value == item) {
                j = i;
                return false;
            }
        })

        if (j > -1) arrBtn.splice(j, 1);


    }
});
/*
* @author: wj
* @description: 参与类型单人多人改变
* @date: 2019/3/13 10:37
* @param
* @return
*/
layForm.on('radio(participateType)', function(data){
    partType = data.value;
    if (partType == 1) {
        $("input[name='operationType']").removeAttr("checked");
        $("input[name='operationType']").attr("disabled", "true");
        opType = 1;
    } else if (partType == 2) {
        $("input[name='operationType']").removeAttr("disabled")
        $("input[name='operationType'][value='4']").prop("checked", "true")
        opType = 4
      }

    layForm.render("radio");
});

/*
* @author: wj
* @description: 操作类型改变
* @date: 2019/3/13 17:01
* @param
* @return
*/
layForm.on('radio(operationType)', function(data){
    opType = data.value;
    var otValue = $("input[name='participateType']:checked").val()//参与类型
        ,opValue = data.elem.value
        ,newCheckVValue = []
        ,formValue = {};
    if(("2" === otValue && "1" === opValue) || ("2" === otValue && "2" === opValue)){
        $.each(arrBtn, function (i, item) {
            if(10 === item || 20 === item){
                newCheckVValue.push(item);
            }
        });
        arrBtn.length = 0;
    }
    if(newCheckVValue.length > 0){
        $("input[type='checkbox']").removeAttr("checked");
        $.each(newCheckVValue, function (i, item) {
            formValue["btnType" + item] = true;
            arrBtn.push(item);
        });
        layForm.val("nodeForm", formValue);
    }else{
        $("input[type='checkbox']").removeAttr("checked");
    }
});

/*
* @author: wj
* @description: 结果送达人员改变
* @date: 2019/3/13 16:35
* @param
* @return
*/
layForm.on('radio(notifyPerson)', function(data){
    notifyPerson = data.value;
    layForm.render("radio");
})

/*
* @author: wj
* @description: 活动配置保存
* @date: 2019/3/5 15:59
* @param
* @return
*/
function saveNode() {
    var url = '/wf/activity/saveActivity';
    var authorityData = []
    var btns = JSON.stringify(arrBtn).replace("[", "")
    btns = btns.replace("]", "");
    if($(flowchart.currentNode).attr("code") == 'end'){
        partType = notifyPerson;
    }
    authorityData = JSON.parse(arrAuths.val());
    if (!authorityData) {
        authorityData = [];
    }

    var nodeData = {
        "wfActivity": {
            "wfaId": $(flowchart.currentNode).attr("id")
            , "wfId": wfId
            , "participateType": partType
            , "operationType": opType
            , "positionX": $(flowchart.currentNode).css("left").replace(/px/, "")
            , "positionY": $(flowchart.currentNode).css("top").replace(/px/, "")
            , "activityName": $("#node_Name").val()
            , "activityCode": $(flowchart.currentNode).attr("code")
            , "activityButtons": btns
        },
        "wfActivityAuthorityList": authorityData
    };

    if(nodeData.wfActivityAuthorityList.length == 0 && $(".endHide").css("display") != "none") {
        layer.alert("请先选择该活动的执行者")
        return;
    }

    if (partType == 1) {
        if (nodeData.wfActivityAuthorityList.length != 1 || nodeData.wfActivityAuthorityList[0].activityType != "5") {
            if (!(nodeData.wfActivityAuthorityList[0].activityType == 6 && (nodeData.wfActivityAuthorityList[0].functionId == 1 || nodeData.wfActivityAuthorityList[0].role == 1))) {
                layer.alert("“单人”类型必须且只能选择一个明确的用户！")
                return;
            }
        }
    }
    if (partType == 2 && opType == 1) {
        insertToDb(url,nodeData);

        ActHttpRequest('/sys-user/listAllCurActivityUsers', {
            "id":nodeData.wfActivity.wfaId
        }, function (data) {
            if (data.OK != "OK") {
                layer.msg(data.message);
                return;
            }

            var users = data.userList;
            if(users.length > 1) {
                layer.open({
                    type: 1
                    , content: $('#userOrder')
                    , resize: false
                    , area: ['350px', '600px']
                    , title: '【多人 串行】 办理顺序'
                    , btn: ['确定', '取消']
                    , success: function (layero, index) {

                        layui.use('table', function () {
                            var table = layui.table;

                            table.init('tableUsers', {
                                height: '480',
                                data: users,
                                limit: 999,
                                done: function () {
                                }
                            });

                            table.on('tool(tableUsers)', function(obj){
                                var layEvent = obj.event;
                                var i = obj.tr[1].innerText - 1
                                var iTemp = users[i]

                                if(layEvent === 'moveUp'){
                                    if (i == 0) {
                                        layer.msg("已经排在最上面",{icon: 7})
                                        return
                                    }
                                    users[i] = users[i - 1]
                                    users[i - 1] = iTemp
                                    layer.msg("操作成功",{icon: 6})
                                } else if(layEvent === 'moveDown'){
                                    if (i == users.length - 1) {
                                        layer.msg("已经排在最下面",{icon: 7})
                                        return
                                    }
                                    users[i] = users[i + 1]
                                    users[i + 1] = iTemp
                                    layer.msg("操作成功",{icon: 6})
                                }

                                table.reload('tableUsers', {data: users})
                            });

                        });
                    }
                    , yes: function (index, layero) {

                        $.each(users, function (i, item) {
                            item.activityId = nodeData.wfActivity.wfaId
                            item.activityType = 5
                            item.role = item.id
                        })

                        nodeData.wfActivityAuthorityList = users;

                        console.log(nodeData)
                        // return
                        insertToDb(url, nodeData)
                        layer.close(index)
                    }
                    , end: function () {
                        $('#userOrder').css('display', 'none')

                    }
                });

            } else {
                insertToDb(url, nodeData)
            }

        }, null, null, null, '处理中。。。', true);

    } else {
        insertToDb(url, nodeData)
    }
}
/*
* @author: wj
* @description: 保存活动节点数据
* @date: 2019/3/20 14:10
* @param
* @return
*/
function insertToDb(url, nodeData) {

    ActHttpRequest(url, {"reqData": JSON.stringify(nodeData)}, function (data) {
        if (data.OK != "OK") {
            layer.msg(data.message);
            return;
        }
        $("#" + $(flowchart.currentNode).attr("id")).find('.activity_title > div:first').html($("#node_Name").val());
        $("#" + $(flowchart.currentNode).attr("id")).attr("title", "【执行人】" + getExecutor($(flowchart.currentNode).attr("id")))
        layer.msg('保存成功');
        closeLayer();

        // saveau();
    }, null, null, null, '保存中。。。', false);
}
/*
* @author: wj
* @description: 删除活动节点
* @date: 2019/3/6 14:26
* @param
* @return
*/
function deleteActivity() {

    if ($(flowchart.currentNode).attr("code") == "001") {
        layer.msg("开始后的第一个节点不可删除")
        return
    }

    var url = '/wf/activity/delActivity'

    layer.confirm('删除后不可恢复，是否继续？', {icon: 2, title: '删除确认'}, function (index) {

        ActHttpRequest(url, {
            id: $(flowchart.currentNode).attr("id")
        }, function (data) {
            if (data.OK !== "OK") {
                layer.msg(data.message);
                return;
            }

            flowchart.instance.remove($(flowchart.currentNode).attr("id"))
            flowchart.currentNode = {}

            layer.msg("删除成功");
            closeLayer();

        }, null, null, null, '处理中。。。', true);
    });
}

/**
 * 根据“参与者选择方式”修改页面显示元素
 * @param type
 */


// function changeSelectedValue(data) {
//     var formId = data.formId;
//     var formName = data.formName;
//
//     if (data.name == "formEditName") {
//         $("#formEditId").val(formId);
//     } else if (data.name == "formViewName") {
//         $("#formViewId").val(formId);
//     } else {
//         $("#formPrintId").val(formId);
//     }
//     $('#' + data.name).val(formName);
// }
/*
* @author: wj
* @description: 编辑参与者
* @date: 2019/3/6 17:01
* @param
* @return
*/
function tableAuthInit(){
    layui.use('table', function () {
        var table = layui.table;
        var tableData = arrAuths.val()
        if (tableData != "") {
            tableData = JSON.parse(tableData)
        }
        // console.log(tableData)
        table.init('tableAuth', {
            height: '197',
            data: tableData,
            limit: 999,
            done: function () {
                $("[data-field='btnMove']").children().each(function (index) {

                    if($.trim($(this).text())=="增加按钮") {
                            $(this).html('<button class="layui-btn layui-btn-normal layui-btn-sm" onclick="openAuthTree();">\n' +
                                '<i class="layui-icon">&#xe642;</i> 编辑\n' +
                                '</button>')
                    }
                })
            }
        });
    });
}
/*
* @author: wj
* @description: 打开参与者编辑页面
* @date: 2019/3/5 13:37
* @param
* @return
*/
function openAuthTree() {
        layer.open({
            type: 2
            , title: '选择参与者'
            , content: '../../../../base/workFlow/workFlow/tree_Diagram.html?wfId=' + wfId + "&wfaId=" + $(flowchart.currentNode).attr("id")
            , area: ['950px', '627px']
            , id: "divTree"
            , success: function(layero, index) {
                $("#divTree").val(index)
            },
            cancel: function () {

            }
        })

}

table.on('tool(tableAuth)', function(obj){
    var layEvent = obj.event;

    if(layEvent === 'removeAuth'){
        var atype = obj.data.activityType
        var arrTemp = JSON.parse(arrAuths.val())

        var iRm = obj.tr.selector.replace(/.*data-index="([0-9]*)"]$/, '$1')
        arrTemp.splice(iRm, 1)

        arrAuths.val(JSON.stringify(arrTemp))
        // tableAuthInit();
        var table = layui.table;
        table.reload('tableAuth', {
            data: JSON.parse(arrAuths.val())
        })
    }
});

